﻿CREATE FUNCTION dbo.f_InstallmentsTotal
(@LoanID int)
RETURNS int   BEGIN 

DECLARE @Ret int, @HousePmt int

SELECT @Ret = SUM(Term)
FROM dbo.v_TradeReferences
WHERE LoanID = @LoanID AND	AccType = 'i' AND
			Term > 0  AND	(Ballance / Term > 3) AND
			AccountState = 1 AND IsTradeIn = 0

IF NOT dbo.f_MortgageStatus(@LoanID) IS NULL
	SELECT @HousePmt = SUM(A.HousePayment)	FROM dbo.t_Address A
	INNER JOIN dbo.t_Loan_Borrower LB ON A.BorrowerID = LB.BorrowerID
	WHERE LB.LoanID = @LoanID --AND HouseHoldTypeID IN(3,4)

RETURN ISNULL(ISNULL(@Ret,0) - ISNULL(@HousePmt,0),0)

END
